import { useState } from "react";
import { useEffect } from 'react';
import { useNavigate } from "react-router-dom";
import { AuthContext } from "@/App";
import { useContext } from "react";
import { toast } from "sonner";

import axios from '../utils/axios';

export default function Login() {
  const [isConnecting, setIsConnecting] = useState(false);
  const [error, setError] = useState("");
  const navigate = useNavigate();
  const { setIsAuthenticated } = useContext(AuthContext);

  // 检查登录状态
  useEffect(() => {
    // 修改检查登录状态的请求
    const checkAuth = async () => {
      try {
        const response = await axios.post('/api/check-auth', {});

        console.log('Auth check response:', response.data);
        if (response.data.isAuthenticated) {
          setIsAuthenticated(true);
          toast.success("您已登录");
          navigate('/dashboard');
        }
      } catch (error) {
        console.log('未登录或认证失败:', error);
      }
    };

    checkAuth();
  }, [navigate, setIsAuthenticated]);

  const connectWallet = async () => {
    try {
      setIsConnecting(true);
      setError("");

      // 先检查是否已登录
      try {
        const authCheck = await axios.post('api/check-auth', {});
        console.log('Pre-login auth check:', authCheck.data);

        if (authCheck.data.isAuthenticated) {
          setIsAuthenticated(true);
          navigate('/dashboard');
          return;
        }
      } catch (authError) {
        console.log('未登录，继续执行钱包连接流程');
      }

      console.log("Preparing to connect wallet...");

      if (!window.ethereum) {
        throw new Error('请安装MetaMask钱包');
      }

      // // Ensure we're on the correct network
      // await window.ethereum.request({
      //   method: 'wallet_switchEthereumChain',
      //   params: [{ chainId: '0x7A69' }], // Replace with your chainId
      // });

      // 使用web3获取账户
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
      const address = accounts[0];

      // 向后端发送登录请求
      const response = await axios.post('http://localhost:3000/api/login', {
        address
      }, {
        withCredentials: true,
        headers: {
          'Content-Type': 'application/json'
        }
      });

      console.log("Response: ", response);

      if (response.status !== 200) {
        throw new Error(response.data.error || '登录失败');
      }

      if (response.data.success) {
        setIsAuthenticated(true);
        toast.success("钱包连接成功");
        navigate("/dashboard");
      } else {
        if (response.data.role === '0') {
          toast.error("未注册的用户");
        }
      }


    } catch (err) {
      setError("连接钱包失败");
      console.error(err);
    } finally {
      setIsConnecting(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-50 p-4">
      <div className="w-full max-w-md">
        <div className="rounded-md border border-[#673AB7] bg-white shadow-md">
          <div className="h-2 rounded-t-md bg-[#673AB7]"></div>
          <div className="p-8">
            <h1 className="mb-6 text-center text-lg font-bold">云上医疗</h1>
            <div className="flex flex-col items-center">
              <button
                onClick={connectWallet}
                disabled={isConnecting}
                className="w-full rounded-md bg-[#673AB7] py-2 px-4 text-white hover:bg-[#9575CD] focus:outline-none focus:ring-2 focus:ring-[#673AB7] focus:ring-offset-2 disabled:opacity-50"
              >
                {isConnecting ? '连接中...' : '连接MetaMask钱包'}
              </button>
              {error && (
                <p className="mt-4 text-sm text-red-500">{error}</p>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
